package org.ptkparty.client.activity;

import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;

import org.ptkparty.client.ClientFactory;
import org.ptkparty.client.model.ScaleProxy;
import org.ptkparty.client.request.ScaleRequest;
import org.ptkparty.client.view.scales.ScalesView;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.adapters.HasDataEditor;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.gwt.client.RequestFactoryEditorDriver;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class ScalesActivity implements Activity {

	private static Driver driver = GWT.create(Driver.class);

	interface Driver extends RequestFactoryEditorDriver<List<ScaleProxy>, HasDataEditor<ScaleProxy>> {
	}

	private ClientFactory clientFactory;
	private ScaleRequest request;
	private ScalesView view;

	public ScalesActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		view = clientFactory.getScalesView();
		view.setPresenter(this);
		panel.setWidget(view);

		driver.initialize(clientFactory.getEventBus(), clientFactory.getFactory(), view.asEditor());

		clientFactory.getFactory().scaleRequest().getAllScale().fire(new Receiver<List<ScaleProxy>>() {

			@Override
			public void onSuccess(List<ScaleProxy> response) {
				request = clientFactory.getFactory().scaleRequest();

				driver.edit(response, request);

				request.save(view.asEditor().getList()).to(new Receiver<Void>() {

					@Override
					public void onConstraintViolation(Set<ConstraintViolation<?>> violations) {
						driver.setConstraintViolations(violations);
					}

					@Override
					public void onSuccess(Void response) {

					}

				});
			}
		});
	}

	@Override
	public String mayStop() {
		return null;
	}

	@Override
	public void onCancel() {
	}

	@Override
	public void onStop() {
	}

	public ScaleProxy addScale() {
		return request.create(ScaleProxy.class);
	}

	public void delete(final ScaleProxy selectedObject) {
		if (selectedObject != null) {
			clientFactory.getFactory().scaleRequest().remove().using(selectedObject).fire(new Receiver<Void>() {

				@Override
				public void onSuccess(Void response) {
					view.removeUserEditor(selectedObject);
				}

			});
		}
	}

	public void save() {
		driver.flush().fire();
	}

}
